package cn.wolfcode.luowowo.article.service.impl;

import cn.wolfcode.luowowo.article.domain.Answer;
import cn.wolfcode.luowowo.article.domain.AnswerContent;
import cn.wolfcode.luowowo.article.mapper.AnswerContentMapper;
import cn.wolfcode.luowowo.article.mapper.AnswerMapper;
import cn.wolfcode.luowowo.article.query.AnswerQuery;
import cn.wolfcode.luowowo.article.service.IAnswerService;
import cn.wolfcode.luowowo.cache.service.IAnswerRedisService;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.comment.service.ICommunityCommentService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class AnswerServiceImpl implements IAnswerService {

    @Autowired
    private AnswerMapper answerMapper;
    @Autowired
    private AnswerContentMapper answerContentMapper;

    @Reference
    private ICommunityCommentService commentService;

    @Reference
    private IAnswerRedisService answerRedisService;

    @Reference
    private IUserInfoRedisService userInfoRedisService;
    @Override
    public PageInfo query(AnswerQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());

        return new PageInfo(answerMapper.selectForQuery(qo));
    }

    @Override
    public Answer getContent(Long id) {
        Answer answer = answerMapper.selectByPrimaryKey(id);
        answer.setContent(answerContentMapper.selectByPrimaryKey(answer.getId()));
        return answer;
    }

    @Override
    public void upByStatus(Answer answer) {
        if(answer.getStatus()==3){
            answerMapper.updateByGold(answer.getId());

        }else {
            answerMapper.updateByPrimaryKey(answer);
        }
    }

    @Override
    public List<Answer> getAnswerById(Long id) {
        List<Answer> answers = answerMapper.selectByAskId(id);
        for (Answer answer : answers) {
            answer.setComments(commentService.listById(answer.getAsk().getId(),answer.getId()));
        }
        return answers;
    }

    @Override
    public void save(Answer answer, String contentId) {

        //添加回答信息
        answerMapper.insert(answer);
        //添加回答内容
        AnswerContent content = new AnswerContent();
        content.setId(answer.getId());
        content.setContent(contentId);
        answerContentMapper.insert(content);
        answerRedisService.save(answer.getId());



    }

    @Override
    public List<Answer> listAll() {
        return answerMapper.selectAll();
    }
}
